//
//  ProductView.m
//  iFlower
//
//  Created by khanh nguyen on 7/23/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "ProductView.h"
#import "ProductDetailView.h"
#import "Request.h"
#import "Product.h"
#import "iFlowerAppDelegate.h"
#import "ProductCell.h"
#import "MyAccountView.h"
#import "LoginView.h"
#import "RegisterView.h"

@interface ProductView (Private)
- (void)loadContentForVisibleCells;
@end

@implementation ProductView
@synthesize productCell = _productCell;
@synthesize tableview = _tableview;
@synthesize catId;
@synthesize products = _products;
@synthesize titleText = _titleText;
@synthesize lblTitle = _lblTitle;
@synthesize btnRegister;

-(IBAction)buttonBack:(id)sender
{
	[self.navigationController popViewControllerAnimated:YES];
}
-(IBAction) buttonMenu
{
	[self.navigationController popToRootViewControllerAnimated:YES];
}
-(IBAction) buttonMyAccount
{
	if ([[iFlowerAppDelegate shareDelegate] logined]) {
		MyAccountView * account = [[MyAccountView alloc] initWithNibName:@"MyAccountView" bundle:nil];
		[self.navigationController pushViewController:account animated:YES];
		[account release];
	}
	else {
		LoginView * login = [[LoginView alloc] initWithNibName:@"LoginView" bundle:nil];
		[self.navigationController pushViewController:login animated:YES];
		[login release];		
	}
	
}
-(IBAction) buttonRegister
{
	RegisterView * registerView = [[RegisterView alloc] initWithNibName:@"RegisterView" bundle:nil];
	[self.navigationController pushViewController:registerView animated:YES];
	[registerView release];
}

/*-(void)buttonBuy_Now:(id)sender
{
	UIButton* b = (UIButton*)sender;
	UITableViewCell* c = (UITableViewCell*)[[b superview]superview];
	NSIndexPath* indexPath = [_tableview indexPathForCell:c];
	ProductDetailView * detail = [[ProductDetailView alloc] initWithNibName:@"ProductDetailView" bundle:nil];
	detail.titleText = _titleText;
	detail.product = [_products objectAtIndex:indexPath.row];
	[self.navigationController pushViewController:detail animated:YES];
	[detail release];
}*/
#pragma mark Table view methods


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
   
	return [_products count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	static NSString *CellIdentifier = @"Cell";
	
	ProductCell *cell = (ProductCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	if (cell == nil) {
		[[NSBundle mainBundle] loadNibNamed:@"ProductCell" owner:self options:nil];
		cell = _productCell;
	}
	Product* product = [_products objectAtIndex:indexPath.row];
	//UIImageView * image = (UIImageView*)[cell viewWithTag:1];
	UILabel * first = (UILabel *)[cell viewWithTag:2];
	first.text = product.product;
	UILabel * second = (UILabel *)[cell viewWithTag:3];
	second.text = product.price;
	//UIButton * button = (UIButton *)[cell viewWithTag:4];
	cell.photo = (UIImageView*)[cell viewWithTag:1];
	cell.item = product;
	[cell loadImage];
	//first.text = [[tableData objectAtIndex:indexPath.row] objectForKey:@"time"];
	//second.text = [[tableData objectAtIndex:indexPath.row] objectForKey:@"videoname"];
	//third.text = [[tableData objectAtIndex:indexPath.row] objectForKey:@"description"];
	//button.titleLabel.text = [NSString stringWithFormat:@"%d",indexPath.row];
	//[button addTarget:self action:@selector(buttonBuy_Now:) forControlEvents:UIControlEventTouchUpInside];
	//image.image = [images objectAtIndex:indexPath.row];
	//[button addTarget:self action:@selector(nextAction:) forControlEvents:UIControlEventTouchUpInside];
	
	//image.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[[tableData objectAtIndex:indexPath.row]objectForKey:@"avatar"]]]];
	return cell;
}

// Override to support row selection in the table view.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	[self.tableview deselectRowAtIndexPath:indexPath animated:YES];
	ProductDetailView * detail = [[ProductDetailView alloc] initWithNibName:@"ProductDetailView" bundle:nil];
	detail.titleText = _titleText;
	detail.product = [_products objectAtIndex:indexPath.row];
	[self.navigationController pushViewController:detail animated:YES];
	[detail release];
	
	// Navigation logic may go here -- for example, create and push another view controller.
	// AnotherViewController *anotherViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherView" bundle:nil];
	// [self.navigationController pushViewController:anotherViewController animated:YES];
	// [anotherViewController release];
}



/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */


/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
 
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source.
 [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
 }   
 else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
 }   
 }
 */


/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */


/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */
- (NSString *)flattenHTML:(NSString *)html {
	
    NSScanner *theScanner;
    NSString *text = nil;
	
    theScanner = [NSScanner scannerWithString:html];
	
    while ([theScanner isAtEnd] == NO) {
		
        // find start of tag
        [theScanner scanUpToString:@"<" intoString:NULL] ; 
		
        // find end of tag
        [theScanner scanUpToString:@">" intoString:&text] ;
		
        // replace the found tag with a space
        //(you can filter multi-spaces out later if you wish)
        html = [html stringByReplacingOccurrencesOfString:
				[ NSString stringWithFormat:@"%@>", text]
											   withString:@" "];
		
    } // while //
    
    return [html stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
	
}
- (void) contentLoaded:(NSNotification*) notification
{
	NSLog(@"content loaded");
	[[NSNotificationCenter defaultCenter] removeObserver:self];
	_products = [[NSMutableArray alloc] initWithCapacity:[[[Request sharedRequest] entries] count]];
    NSDictionary * temp = (NSDictionary*)[[[Request sharedRequest] entries]objectAtIndex:0];
    // NSLog(@"%@",temp);
    NSDictionary * productsDict = [temp objectForKey:@"products"];
    //NSLog(@"%@",productsDict);
	for (NSDictionary* dictionary in productsDict)
	{
        //NSLog(@"%@",dictionary);
		Product* entry = [[Product new] autorelease];
		if (entry != nil)
		{
			if([dictionary objectForKey:@"productid"]!=[NSNull null])
				entry.productId = [dictionary objectForKey: @"productid"];
			if([dictionary objectForKey:@"productcode"]!=[NSNull null])
				entry.productCode = [dictionary objectForKey: @"productcode"];
			if([dictionary objectForKey:@"product"]!=[NSNull null])
				entry.product = [dictionary objectForKey: @"product"];
			if([dictionary objectForKey:@"fulldescr"]!=[NSNull null])
				entry.fulldesc = [self flattenHTML:[dictionary objectForKey: @"fulldescr"]];
			if([dictionary objectForKey:@"list_price"]!=[NSNull null])
				entry.price = [dictionary objectForKey: @"list_price"];
			if([dictionary objectForKey:@"descr"]!=[NSNull null])
				entry.shortdesc = [dictionary objectForKey: @"descr"];
			if([dictionary objectForKey:@"provider"]!=[NSNull null])
				entry.provider = [dictionary objectForKey:@"provider"];
			if([dictionary objectForKey:@"tmbn_url"]!=[NSNull null])
				entry.thumbnailURL = [NSURL URLWithString: [dictionary objectForKey: @"tmbn_url"]];
			[_products addObject: entry];
		}
	}
	NSLog(@"LOAD OK");
    iFlowerAppDelegate *appDelegate = [iFlowerAppDelegate shareDelegate];
	[appDelegate hideLoadingView];
	[_tableview reloadData];
}
- (void) contentFailed:(NSNotification*) notification
{
	[[NSNotificationCenter defaultCenter] removeObserver:self];
	NSLog(@"content failed");
    iFlowerAppDelegate *appDelegate = [iFlowerAppDelegate shareDelegate];
	[appDelegate hideLoadingView];
}
#pragma mark -
#pragma mark View lifecycle
- (void) viewWillAppear:(BOOL)animated
{
	[super viewWillAppear:animated];
	if([[iFlowerAppDelegate shareDelegate] logined])
	{
		self.btnRegister.enabled = NO;
	}else {
		self.btnRegister.enabled = YES;
	}
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	_tableview.rowHeight = 100;
	_tableview.backgroundColor = [UIColor clearColor];
	_lblTitle.text = _titleText;
    
    [[iFlowerAppDelegate shareDelegate] showLoadingView];
		
	[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(contentLoaded:) name: @"ContentLoaded" object: nil];
	[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(contentFailed:) name: @"ContentFailed" object: nil];
	
	[[Request sharedRequest] getFlowerByCategory:self.catId];
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
    self.btnRegister = nil;
}


- (void)dealloc {
	[btnRegister release];
	[[NSNotificationCenter defaultCenter] removeObserver:self];
	[_titleText release];
	[_lblTitle release];
	[_productCell release];
	[_tableview release];
    [super dealloc];
}

#pragma mark -
#pragma mark UIScrollViewDelegate methods

// These methods are adapted from
// http://idevkit.com/forums/tutorials-code-samples-sdk/2-dynamic-content-loading-uitableview.html

- (void)loadContentForVisibleCells
{
    NSArray *cells = [_tableview visibleCells];
    [cells retain];
   /*for (int i = 0; i < [cells count]; i++) 
    { 
		
    }*/
    [cells release];
}


- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView; 
{
    // Method is called when the decelerating comes to a stop.
    // Pass visible cells to the cell loading function. If possible change 
    // scrollView to a pointer to your table cell to avoid compiler warnings
    [self loadContentForVisibleCells]; 
}


- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate;
{
    if (!decelerate) 
    {
        [self loadContentForVisibleCells]; 
    }
}

@end
